/**
 * 
 */
package com.star.servlet;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.file.Files;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: ImageServlet
 * @Description: TODO
 * @author starhq
 * @createtime 2014年10月28日 下午4:22:51
 * @email : jian.wang@shinsoft.net
 * @modify by TODO
 * @resaon
 * @edittime
 * @version 1.0
 * @copyright shinsoft
 */
public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private String imagePath;

	@Override
	public void init() throws ServletException {
		this.imagePath = "";
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String requestedImage = req.getPathInfo();

		if (requestedImage == null) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		File image = new File(imagePath, URLDecoder.decode(requestedImage,
				"UTF-8"));

		if (!image.exists()) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		String contentType = getServletContext().getMimeType(image.getName());

		if (contentType == null || !contentType.startsWith("image")) {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		resp.reset();
		resp.setContentType(contentType);
		resp.setHeader("Content-Length", String.valueOf(image.length()));

		Files.copy(image.toPath(), resp.getOutputStream());
	}

}
